package cn.com.youjile.observer;

import cn.com.youjile.entity.MsgInfo;
import io.netty.channel.ChannelHandlerContext;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author youjile
 * @CreateDate 2021/3/12
 * @Describe 消息观察者模式，状态改变后执行的操作
 */
public class MsgSubject {

    private List<MsgObserver> observers = new ArrayList<MsgObserver>();
    private ChannelHandlerContext ctx;
    private MsgInfo msg;
    private static MsgSubject msgSubject;

    private MsgSubject(){

    }

    public static MsgSubject getInstance(){
        if(msgSubject == null) {
            msgSubject = new MsgSubject();
        }
        return msgSubject;
    }

    public void setState(ChannelHandlerContext ctx, MsgInfo msg) {
        this.ctx = ctx;
        this.msg = msg;
        notifyAllObservers();
    }

    public void attach(MsgObserver observer){
        observers.add(observer);
    }

    private void notifyAllObservers(){
        for (MsgObserver observer : observers) {
            observer.update(ctx, msg);
        }
    }

}
